#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib> //stdlib.h
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024
using namespace std;

void Writer(int wfd)
{
    string str = "hello world";
    pid_t self = getpid();
    int number =0;
    char buffer[NUM];
    int count=10;
    while(count)
    {
        snprintf(buffer,sizeof(buffer),"%s-%d-%d",str.c_str(),self,number);
        cout<<buffer<<endl;
        write(wfd,buffer,strlen(buffer));
        number++;
        count--;
        sleep(1);
    }

}
void Reader(int wfd)
{
    char buffer[NUM];
    int count =10;
    while(count--)
    {
    int i = read(wfd,buffer,sizeof(buffer));
    if(i>0)
    {
        buffer[0]='\0';
        cout<<"father gets a message:" <<buffer<<endl;
    }
    else if(i==0)
    {
        printf("father read file done!\n");
        break;
    }
    else
    {
        break;
    }
    }   
}
int main()
{
    int pipefd[N];
    int n = pipe(pipefd);
    if(n<0)
        return 1;
    pid_t id = fork();
    if(id<0)
        return 2;
    if(id == 0)
    {
        //Child
        close(pipefd[0]);
        Writer(pipefd[1]);
        close(pipefd[1]);
    }
    //father
    close(pipefd[1]);
    Reader(pipefd[0]);
    

    pid_t rid = waitpid(id,nullptr,0);
    if(rid<0)
        return 3;

    close(pipefd[0]);

    return 0;

}
